import {Component, HostBinding, Injector, OnInit, AfterViewInit, ViewEncapsulation, ElementRef} from '@angular/core';
import {Logger} from './shared/utils';
import {Title} from '@angular/platform-browser';
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
import {BroadcastService} from './shared/services/common/broadcast-service';
import {CacheService} from './shared/services/common/cache-service';
import {Router} from '@angular/router';
import {appInjector} from './shared/utils/app-injector';
import {environment} from '../environments/environment';
import {CookieHelper} from './shared/utils';
import {BroadcastEvent} from './shared/models/common/broadcast-events';
import zh from '@angular/common/locales/zh';
import * as $ from 'jquery';
import {registerLocaleData} from '@angular/common';




@Component({
  selector: 'body',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less'],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent implements OnInit, AfterViewInit {
  inputFocus: boolean = false;
  systemName;
  isCollapsed = false;
  logoName = 'logo1.png';

  @HostBinding('class') public cssClass: string = '';

  constructor(private router: Router, private injector: Injector, private titleService: Title,
              private elementRef: ElementRef, private cacheService: CacheService,
              private translateService: TranslateService, private broadcastService: BroadcastService) {
    appInjector(injector);
    this.cacheService.setGlobalPrefix(`cache-${environment.appName}-${environment.envName}-${environment.appVersion}-`);
    this.initLanguage();
  }

  ngOnInit(): void {
    Logger.log('app - ngOnInit');
    this.systemName = environment.appName;
    this.disableAjaxCache();
    registerLocaleData(zh);
  }

  ngAfterViewInit(): void {
    this.fixWeChatScrollBugInIOS();
  }

  initLanguage(): void {
    let activeLanguage = CookieHelper.get(environment.languageCookieKey);
    if (!activeLanguage) {
      activeLanguage = environment.defaultLanguage;
    }

    environment.activeLanguage = activeLanguage;
    this.translateService.onLangChange.subscribe((event: LangChangeEvent) => {
      this.refreshPageTitle();
    });
    this.translateService.setDefaultLang(environment.defaultLanguage);
    this.translateService.use(activeLanguage);
  }

  registerEventListeners(): void {
    this.broadcastService.on<string>(BroadcastEvent.RedirectToLoginPage).subscribe(redirectUrl => {
      Logger.log('Receive broadcast event => Navigate to login page');
      if (redirectUrl) {
        this.router.navigate(['/login'], {queryParams: {redirectUrl: redirectUrl}});
      } else {
        this.router.navigate(['/login']);
      }
    });
  }

  /**
   * 问题: ios12+，微信6.7.4版本存在bug,键盘收回时,界面没有恢复,底下出现空白区域,并导致光标位置错乱,再次点击输入框区域时无法focus
   * 解决方案: 当input失焦,键盘收回后,滚动一下页面就可以使页面恢复正常
   * 补充: 当在手机号与验证码之间切换输入时,会同时触发前输入框的blur和后输入框focus,这个时候触发滚动,页面会出现较大跳跃,
   * 因此通过inFocus 和 setTimeout 判断,是切换input还是真正blur,真正blur的时候,再滚动页面
   */
  fixWeChatScrollBugInIOS(): void {
    if (!(/iphone|ipod|ipad/i).test(navigator.userAgent.toLowerCase())) {
      return;
    }
    $(this.elementRef.nativeElement).on('blur', 'input,textarea,select', () => {
      this.inputFocus = false;
      setTimeout(() => {
        if (this.inputFocus) {
          return;
        }
        // 当input 失焦时,滚动一下页面就可以使页面恢复正常
        this.scrollWechatPage();
      }, 200);
    }).on('focus', 'input,textarea,select', () => {
      this.inputFocus = true;
    });
  }

  scrollWechatPage(): void {
    let curPosition, timer;
    let speed = 1;//页面滚动距离
    timer = setInterval(function() {
      curPosition = document.documentElement.scrollTop || document.body.scrollTop;
      curPosition -= speed;
      window.scrollTo(0, curPosition);//页面向上滚动
      curPosition += speed; //speed变量
      window.scrollTo(0, curPosition);//页面向下滚动
      clearInterval(timer);
    }, 1);
  }

  refreshPageTitle(): void {
    this.translateService.get('Shared.appTitleName').subscribe(value => {
      this.titleService.setTitle(value);
    });
  }

  disableAjaxCache(): void {
    //禁用 ajax 请求 cache。 防止IE缓存 ajax 请求，导致内容不刷新
    $.ajaxSetup({
      cache: false
    });
  }
}
